import 'package:get/get.dart';
import 'package:time_manager/utils/timeDeal.dart';

import '../../dict/table_dict.dart';
import '../../utils/DataBaseRecord.dart';
import '../model/item_list_model.dart';

class GlobalData extends GetxController {
  RxList<ItemList> list = <ItemList>[].obs;
  RxList<ItemList> filterList = <ItemList>[].obs;
  var totalTime = 0.obs;
  var todayTime = 0.obs;
  var ceshi = 'fasfa'.obs;
  var startTime = ''.obs;
  var endTime = ''.obs;

  @override
  onInit() async {
    super.onInit();
    fetchData();
  }

  fetchData() async {
    List<dynamic> temp = await DataBaseRecord()
        .query(TableName.timeList.name, orerBy: 'time desc');
    list.value = temp.map((it) => ItemList.fromJson(it)).toList();

    startTime.value =
        TimeUtil().getLocalTime(TimeUtil().startWeek().toString(), format: 'y');
    endTime.value =
        TimeUtil().getLocalTime(TimeUtil().endWeek().toString(), format: 'y');
    setFilterList();
    update();
  }

  changeStart(String val) {
    startTime.value = val;
    setFilterList();
    update();
  }

  changeEnd(String val) {
    endTime.value = val;
    setFilterList();
    update();
  }

  changeCeshi() {
    ceshi.value = 'fasdfa';
  }

  addItem(ItemList item) {
    list.add(item);
    setFilterList();
  }

  deleteItem(int time) {
    list.removeWhere((it) => it.time == time);
    update();
  }

  List<ItemList> getCurrent() {
    final start = TimeUtil().startTime();
    final end = TimeUtil().endTime();
    // print(TimeUtil().getLocalTime(TimeUtil().startWeek().toString()));
    // print(TimeUtil().getLocalTime(TimeUtil().endWeek().toString()));
    todayTime.value = 0;
    return list.where((it) {
      final flag = start < it.time && it.time < end;
      if (flag) {
        todayTime.value = todayTime.value + it.duration;
      }

      return flag;
    }).toList();
  }

  setFilterList() {
    final start =
        DateTime.parse('${startTime.value} 00:00:00').millisecondsSinceEpoch;
    final end =
        DateTime.parse('${endTime.value} 23:59:00').millisecondsSinceEpoch;
    totalTime.value = 0;
    filterList.value = list.where((it) {
      final flag = start < it.time && it.time < end;
      if (flag) {
        totalTime.value = it.duration + totalTime.value;
      }
      return flag;
    }).toList();
    update();
  }

  List<ItemList> get currentList => getCurrent();
}
